<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>任务管理</el-breadcrumb-item>
      <el-breadcrumb-item>任务{{ isAdd }}</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <h1 style="margin-bottom: 15px">{{ isAdd }}任务</h1>
      <el-form
        :model="taskForm"
        ref="taskRef"
        :inline="false"
        size="normal"
        label-width="100px"
      >
        <el-form-item label="父级任务">
          <el-input
            v-model="taskForm.parentId"
            disabled
            style="width: 25%"
          ></el-input>
        </el-form-item>
        <el-form-item label="任务名称">
          <el-input v-model="taskForm.taskname" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="发起人" v-if="creatorUserList == ''">
          <el-select
            v-model="taskForm.creator"
            placeholder="请选择"
            style="width: 25%"
          >
            <el-option
              v-for="(item, i) in creatorUserList"
              :key="i"
              :label="
                item.name +
                '(' +
                item.position.name +
                '/' +
                item.rofessional.name +
                ')'
              "
              :value="item._id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发起人" v-else>
          <el-select
            v-model="taskForm.creator"
            placeholder="请选择"
            style="width: 25%"
          >
            <el-option
              v-for="(item, i) in creatorUserList"
              :key="i"
              :label="
                item.name +
                '(' +
                item.position.name +
                '/' +
                item.rofessional.name +
                ')'
              "
              :value="item._id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="负责人">
          <el-select
            v-model="taskForm.worker"
            placeholder="请选择"
            style="width: 25%"
            multiple
          >
            <el-option
              v-for="(item, i) in userList"
              :key="i"
              :label="
                item.name +
                '(' +
                item.position.name +
                '/' +
                item.rofessional.name +
                ')'
              "
              :value="item._id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="taskForm.status"
            placeholder="请选择"
            style="width: 25%"
            :disabled="!id"
          >
            <el-option label="未开始" :value="0"></el-option>
            <el-option label="进行中" :value="1"></el-option>
            <el-option label="被打回" :value="2"></el-option>
            <el-option label="已完成" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="进度">
          <el-slider
            v-model="taskForm.process"
            :step="10"
            style="width: 70%"
            :disabled="!id"
          >
          </el-slider>
        </el-form-item>

        <el-form-item label="已有附件">
          <span v-for="(item, index) in taskForm.fileAddress" :key="index">
            <span v-if="item.files.length != 0">
              <span v-for="(item2, index) in item.files" :key="index">
                <el-tag
                  disable-transitions
                  effect="dark"
                  closable
                  v-if="item2 != null"
                  @close="fileDel(item2, taskForm._id)"
                >
                  {{ item2.originalname }}
                </el-tag>
              </span>
            </span>
          </span>
        </el-form-item>

        <!-- <el-form-item label="附件上传">
          <el-upload
            style="width: 500px"
            class="upload-demo"
            :action="$http.defaults.baseURL + '/uploads'"
            :headers="getAuthHeader()"
            :before-remove="beforeRemove"
            :limit="9"
            :on-exceed="handleExceed"
            :file-list="taskForm.fileAddress.files"
            :on-success="handleSuccess"
            :on-remove="handleRe"
            name="files"
            multiple
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="附件描述">
          <el-input v-model="fileDescribe" style="width: 80%"></el-input>
        </el-form-item> -->

        <el-form-item label="内容描述">
          <el-input
            type="textarea"
            rows="4"
            v-model="taskForm.describe"
            style="width: 250px; width: 100%"
          ></el-input>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="taskForm.endtime"
            type="datetime"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">{{ isAdd }}</el-button>
          <el-button @click="$router.push('/taskList')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  props: {
    id: {},
    parentId: {},
  },
  data() {
    return {
      //表单
      val: {},
      file: [],
      taskForm: {
        parentId: null,
        taskname: "",
        creator: "",
        worker: [],
        status: 0,
        process: 0,
        describe: "",
        endtime: "",
        isSubmit: 0,
        fileAddress: [],
        grade: 0,
      },
      //成员列表
      userList: [],
      creatorUserList: [],
      //规则
      defaultParams: {
        label: "taskname",
        value: "_id",
        children: "children",
        checkStrictly: true,
      },
      // 附件描述
      fileDescribe:''
    };
  },
  methods: {
    // handleProgress(event, file, fileList) {
    //   console.log(file);
    // },

    //点击表单提交按钮
    async onSubmit() {
      // this.val.describe = this.fileDescribe
      // this.taskForm.fileAddress.push(this.val);
      if (this.id) {
        const res = await this.$http.put(`/task/${this.id}`, this.taskForm);
        if (res.data) {
          this.$router.push("/taskList");
          this.$message({
            message: "编辑成功",
            type: "success",
          });
        }
        return;
      }
      const res = await this.$http.post("/task", this.taskForm);
      if (res.data.status === 401) return this.$message.error(res.data.msg);
      if (res.data) {
        this.$router.push("/taskList");
        this.$message({
          message: "添加成功",
          type: "success",
        });
      }
    },

    //获取成员列表
    async getUserList() {
      const res = await this.$http.get("/other/users");
      this.userList = res.data;
      this.creatorUserList = res.data;
    },

    //获取任务详情信息
    async getTask() {
      const res = await this.$http.get(`/task/${this.id}`);
      this.taskForm = res.data;
      // let parent = await this.$http.get('/other/taskParentid',{ params:res.data })
      // // console.log(parent.data);
      // this.parent = parent.data
    },

    // 删除文件接口
    // async deleteFile(val,path) {
    //   const res = await this.$http.get(
    //     `files/deleteFile/${id}?path=${val.path}&originalname=${val.originalname}`
    //   );
    // },

    // 删除已有文件
    async fileDel(val, id) {
      this.$confirm(`确认要删除文件吗, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          await this.$http.get(
            `files/deleteFile/${id}?path=${val.path}&originalname=${val.originalname}`
          );
          await this.getTask();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //文件上传成功后触发事件
    handleSuccess(res) {
      let id = window.localStorage._id;
      if (!this.val.userId) {
        this.val.userId = id;
      }
      // let data = {
      //   name: res.data[0].originalname,
      //   url: res.data[0].path,
      //   mimetype: res.data[0].mimetype,
      //   destination: res.data[0].destination,
      // };
      let data = res.data[0];
      this.file.push(data);
      this.val.files = this.file;
      this.val.name = window.localStorage.admin;
      this.val.process = this.taskForm.process;
    },
    //删除文件之前事件
    async beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    //文件移除触发事件
    handleRe(file, fileList) {
      this.taskForm.fileAddress = fileList;
    },
    //限制个数
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 9 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },

    //获取父级任务选择
    // async getParentIdList() {
    //   let res = await this.$http.get("/other/parentTask");

    //   this.parentIdList = res.data;
    //   // this.setDisable(1, res.data, 4);
    // },

    //存在父级触发事件
    async hanldeParentId() {
      let res = await this.$http(`task/${this.parentId}`);
      this.taskForm.parentId = res.data._id;
      var creator = res.data.worker;
      let intersection = this.userList.filter(function (val) {
        return creator.indexOf(val._id) > -1;
      });
      this.creatorUserList = intersection;
    },
  },
  async created() {
    // this.getParentIdList();
    await this.getUserList();
    this.id && this.getTask();
    this.parentId && this.hanldeParentId();
  },

  watch: {
    // async parent(newval, oldVal) {
    //   if (newval.length > 0) {
    //     //父级id
    //     this.taskForm.parentId = newval[newval.length - 1];
    //     //查询发起人
    //     let res = await this.$http.get(`/task/${newval[newval.length - 1]}`);
    //     this.taskForm.creator = res.data.worker;
    //     this.taskForm.grade = newval.length;
    //   } else {
    //     this.taskForm.parentId = null;
    //     this.taskForm.creator = [];
    //     this.taskForm.grade = 0;
    //   }
    // },
  },
};
</script>

<style lang="less" scoped>
.el-radio {
  margin-right: 0;
}
.el-tag {
  margin: 0 10px 0 0;
}
</style>